import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsSkuListModel.dart';
import 'package:ecy_app_flutter/routes/login/common/DateUtil.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:waterfall_flow/waterfall_flow.dart';

import '../../../constant/constant.dart';
import '../../../ecycommon/utils/EcyRandomUtil.dart';

class EcyGoodsSkuListView extends StatefulWidget {
  final int currentIndex;
  final EcyGoodsSkuListModel skuListModel;
  late _EcyGoodsSkuListViewState currentState;

  final ValueChanged<int> onLoadMore;

  @override
  State<StatefulWidget> createState() {
    currentState =
        _EcyGoodsSkuListViewState(skuListModel, currentIndex, onLoadMore);
    return currentState;
  }

  EcyGoodsSkuListView(this.skuListModel, this.currentIndex, this.onLoadMore);

  reloadData(EcyGoodsSkuListModel newListModel, int page) {
    currentState.reloadData(newListModel, page);
  }
}

class _EcyGoodsSkuListViewState extends State {
  int currentIndex = 0;
  bool requesting = false;
  late EcyGoodsSkuListModel skuListModel;
  final ValueChanged<int> onLoadMore;

  _EcyGoodsSkuListViewState(
      this.skuListModel, this.currentIndex, this.onLoadMore);

  reloadData(EcyGoodsSkuListModel newListModel, int page) {
    if(mounted) {
      setState(() {
        requesting = false;
        skuListModel = newListModel;
        currentIndex = page;
      });
    }
  }

  @override
  void initState() {
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return WaterfallFlow.builder(
      shrinkWrap: true,
      padding: EdgeInsets.all(8.w),
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 8.w,
        mainAxisSpacing: 8.w,
      ),
      itemCount: skuListModel.records.length,
      itemBuilder: (BuildContext context, int index) {
        var item = skuListModel.records[index];
        final imageUrl = item.imageUrl;
        if (imageUrl != null) {
          item.imageUrl = imageUrl.split(",")[0];
        }
        return GestureDetector(
            child: Wrap(
              children: [
                Container(
                  width: (MediaQuery.of(context).size.width - 24.w) / 2,
                  height: (MediaQuery.of(context).size.width - 24.w) / 2,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8.r),
                        topRight: Radius.circular(8.r)),
                    color: Colors.white, //设置背景色为黑色
                  ),
                  child: CachedNetworkImage(
                    width: (MediaQuery.of(context).size.width - 24.w) / 2,
                    height: (MediaQuery.of(context).size.width - 24.w) / 2,
                    key: UniqueKey(),
                    imageUrl: item.imageUrl ?? EcyRandomUtil.randomIconUrl(),
                    httpHeaders: const {"Referer": "https://njlmcc.oss-cn-hangzhou.aliyuncs.com/"},
                    imageBuilder: (context, imageProvider) => Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8.r),
                              topLeft: Radius.circular(8.r)),
                          image: DecorationImage(
                              image: imageProvider, fit: BoxFit.fill)),
                    ),
                    errorWidget: (context, url, error) => ClipRRect(
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(8.r),
                          topRight: Radius.circular(8.r)),
                      child: Image.asset(
                        "assets/images/app_icon1024.png",
                      ),
                    ),
                  )
                ),
                Container(
                  // padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(8.r),
                        bottomRight: Radius.circular(8.r)),
                    color: const Color(0xFFFFFFFF), //设置背景色为黑色
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Container(
                        width:
                            (MediaQuery.of(context).size.width - 24.w) / 2 -
                                16.w,
                        margin:
                            EdgeInsets.only(left: 8.w, right: 8.w, top: 8.h),
                        child: Text(
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w700,
                              color: const Color.fromARGB(255, 38, 38, 38),
                            ),
                            textAlign: TextAlign.left,
                            item.name ?? ""),
                      ),
                      Container(
                        margin: EdgeInsets.only(
                            left: 8.w, right: 8.w, top: 4.h, bottom: 4.h),
                        width:
                            (MediaQuery.of(context).size.width - 24.w) / 2,
                        height: 45.h,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                RichText(
                                  text: TextSpan(
                                    children: [
                                      const TextSpan(
                                        text: '￥',
                                        style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w700,
                                            color: Color(0xFFF55F4E)
                                        )
                                      ),
                                      TextSpan(
                                        text: '${item.salePriceMin ?? item.salePrice ?? 9999.0}',
                                        style: const TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontSize: 18,
                                          fontWeight: FontWeight.w700,
                                          color: Color(0xFFF55F4E),
                                        ),
                                      ),
                                    ],
                                  )
                                ),
                                RichText(
                                  text: TextSpan(
                                    children: [
                                      WidgetSpan(
                                        child: Stack(
                                          children: [
                                            Text(' ￥${item.marketPriceMin ?? item.marketPrice ?? 9999.0}',
                                              style: const TextStyle(
                                                fontFamily: "PingFang SC",
                                                fontSize: 12,
                                                height: 1.2,
                                                fontWeight: FontWeight.w700,
                                                color: Color(0xFF8C8C8C),
                                              ),
                                            ),
                                            Positioned(
                                              left: 4,
                                              right: 0,
                                              top: 8, // 根据实际位置调整
                                              child: Container(
                                                height: 1,
                                                color: const Color(0xFF8C8C8C),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ]
                                  )
                                )
                              ],
                            ),
                            Text(
                              "已售${(item.saleCount)?.toInt() ?? '0'}",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w400,
                                color: const Color(0xFF8C8C8C),
                              ),
                              textAlign: TextAlign.left,
                            )
                          ],
                        )
                      )
                    ],
                  )
                ),
              ],
            ),
            onTap: () {
              var url =
                  "${Constant.H5_BASE_URL}goodsDetailPage.html?goodsid=${item.id ?? ""}&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}";
              EcyRouter.push(context, url, {"h5Title": "商品详情", "h5Url": url});
            });
      },
    );
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
  }

}
